import socket
import threading
import time

def start_server(ip, port):
    # 创建TCP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # server_socket.bind(('127.0.0.1', 8080))  # 绑定IP地址与端口
    server_socket.bind((ip, port))  # 绑定IP地址与端口
    server_socket.listen(5)  # 监听最多5个连接请求
    print("服务器已启动，等待客户端连接...")
    
    while True:
        # 等待客户端连接
        client_socket, client_address = server_socket.accept()
        print(f"客户端 {client_address} 已连接")
        
        # 接收客户端消息
        message = client_socket.recv(1024).decode('utf-8')
        print(f"收到来自客户端的消息: {message}")
        
        # 发送响应消息
        client_socket.send("消息已收到".encode('utf-8'))
        
        # 关闭连接
        # client_socket.close()

if __name__ == "__main__":
    print("thread create")
    thread = threading.Thread( target=start_server, args=("127.0.0.1", 8080, ) )
    print("thread start")
    thread.start()

    # 打开一个文件用于写入。如果文件存在则覆盖，不存在则创建
    with open('log.txt', 'w') as file:
        for i in range(1, 1000):
            time.sleep(1)
            file.write(f'Hello, world!{i}\n')
            file.write('This is another line.\n')
            print("file write")

    thread.join()
    print("Main threfinish")